package com.example.crawler.controller;

import com.dragonsoftbravo.libs.Opr;
import com.dragonsoftbravo.libs.PssLogFactory;
import com.dragonsoftbravo.web.CommonOprController;
import com.example.crawler.exception.CrawlerException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import java.util.UUID;
import java.util.stream.Collectors;

public abstract class BaseController extends CommonOprController {

    /**
     * 参数校验
     * @param br
     */
    public void validateFiled(BindingResult br) {
        if (br.hasErrors()) {
            throw new IllegalArgumentException(br
                    .getAllErrors()
                    .stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .distinct()
                    .collect(Collectors.toList())
                    .toString()
            );
        }
    }

    /**
     * @author pq
     * @description
     * @param
     * @return com.dragonsoftbravo.libs.Opr<java.lang.Void>
     * @date 2022/8/14 17:32
     */
    public Opr<Void> successResult() {
        Opr<Void> opr = new Opr<>();
        opr.setResult(true)
                .setHttpStatus(HttpStatus.OK.value())
                .setCode(String.valueOf(HttpStatus.OK.value()))
                .setMsg(StringUtils.EMPTY);
        return opr;
    }

    public void processException(Opr opr, Exception ex) {
        if (ex instanceof CrawlerException) {
            CrawlerException chatException = (CrawlerException) ex;
            opr.setCode(chatException.getCode());
            opr.setResult(false);
            opr.setMsg(ex.getMessage());
            opr.setHttpStatus(chatException.getStatusCode());
        } else {
            // 系统错误设置RequestId，方便开发人员排查错误日志
            opr.setCode("500");
            opr.setResult(false);
            String requestId = UUID.randomUUID().toString();
            PssLogFactory.getErrorLog().error("[BaseController] Exception details of requestId: " + requestId, ex);
            opr.setMsg(String.format("请求编号: %s, 错误消息: %s", requestId, ex.getMessage()));
            opr.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }
}